package com.nantai.jiafang.nantaijiafang.nt5s.Activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.nt5s.IConstant;
import com.nantai.jiafang.nantaijiafang.nt5s.adapter.QualityRegulationsDataAdapter;
import com.nantai.jiafang.nantaijiafang.nt5s.bean.PaginationRegulations;
import com.nantai.jiafang.nantaijiafang.nt5s.bean.QualityRegulations;
import com.nantai.jiafang.nantaijiafang.nt5s.bean.Regulations;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/***
 *      5s 条例档案
 *      2017-8-17
 * */
public class RegulationsActivity extends AppCompatActivity implements View.OnClickListener {


    private Context mContext;
    private ListView listView;
    private ImageView back,refresh;
    private ProgressDialog progressDialog;
    private QualityRegulationsDataAdapter regulationsDataAdapter;
    private EditText et_regulations;
    private List<QualityRegulations> mList;
    private List<Regulations> mCacheList;
    //2017/08/24 modify
    private Gson gson= new Gson();
    private String type;
    private ImageView imgFisrtPage;
    private ImageView imgPrePage;
    private ImageView imgLastPage;
    private ImageView imgNextPage;
    private TextView tvPageNum;
    private Button btnSelect;
    private int totalPages;
    private int currentPage = 1;
    private int pageSize = 10;
    private String searchStr = "";
    private CheckBox ckAll;
    private CheckBox ckLive;
    private CheckBox ckQua;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regulations);
        mContext = RegulationsActivity.this;
        initView();
        initData();
        Bundle bundle= getIntent().getExtras();
        if(null != bundle){
            type = bundle.getString("type");
            if(TextUtils.isEmpty(type)){
                type="全部";
            }else if(type.equals("质量"))
            {
                ckAll.setVisibility(View.INVISIBLE);
                ckQua.setVisibility(View.INVISIBLE);
                ckLive.setVisibility(View.INVISIBLE);
            }

        }else{
            type="全部";
        }
        getDataFromNet(currentPage,pageSize,searchStr,type);
    }
    private void initView() {
        //2017/08/24 add
        imgFisrtPage = (ImageView) findViewById(R.id.img_first);
        imgLastPage = (ImageView) findViewById(R.id.img_last);
        imgPrePage = (ImageView) findViewById(R.id.img_pre);
        imgNextPage = (ImageView) findViewById(R.id.img_next);
        tvPageNum = (TextView) findViewById(R.id.tv_pagenum);
        btnSelect = (Button) findViewById(R.id.btn_reg_select);
        back=(ImageView)findViewById(R.id.iv_back);
        refresh=(ImageView)findViewById(R.id.iv_refresh);
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("正在获取数据，请稍候");
        listView=(ListView)findViewById(R.id.lv_regulations2);
        et_regulations=(EditText)findViewById(R.id.et_regulations);
        ckAll = (CheckBox)findViewById(R.id.checkAll);
        ckLive = (CheckBox)findViewById(R.id.checkLive);
        ckQua = (CheckBox)findViewById(R.id.checkQua);
//        et_regulations.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if(mList == null || mCacheList == null){
//                    return;
//                }
//                List<Regulations> list = new ArrayList<>();
//                String etInput = et_regulations.getText().toString();
//
//                if("".equals(etInput)){
//                    mList.clear();
//                    mList.addAll(mCacheList);
//                }else {
//                    for (Regulations rs : mCacheList) {
//                        if (rs.getStandard().contains(etInput)) {//contains字符串包含對比
//                            list.add(rs);
//                        }
//                    }
//                    mList.clear();
//                    mList.addAll(list);
//                }
//                regulationsDataAdapter.notifyDataSetChanged();
//            }
//        });
    }

    private void initData() {
        back.setOnClickListener(this);
        refresh.setOnClickListener(this);
        //2017/08/24 add
        imgFisrtPage.setOnClickListener(this);
        imgLastPage.setOnClickListener(this);
        imgPrePage.setOnClickListener(this);
        imgNextPage.setOnClickListener(this);
        btnSelect.setOnClickListener(this);
        ckAll.setOnClickListener(this);
        ckQua.setOnClickListener(this);
        ckLive.setOnClickListener(this);

        mList = new ArrayList<>();
        regulationsDataAdapter = new QualityRegulationsDataAdapter(mContext, mList);
       listView.setAdapter(regulationsDataAdapter);
        listView.setOnItemClickListener((parent,view,position,id)->{
            Log.e("________________", "initData: " );
                QualityRegulations rs = (QualityRegulations) view.getTag(R.id.reg_tag_first);
                Intent it = new Intent(getApplicationContext(),QualityActivity.class);
                Bundle mBundle = new Bundle();
                mBundle.putParcelable("regulation",rs);
                it.putExtras(mBundle);
                setResult(-1001,it);
                finish();
                //startActivity(it);
                //startActivityForResult(it,-100);
                //finish();
        });
    }

//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        Toast.makeText(mContext, "22", Toast.LENGTH_SHORT).show();
//        return super.dispatchTouchEvent(ev);
//    }

//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//            View v = getCurrentFocus();
//            if (isShouldHideInput(v, ev)) {
//
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                if (imm != null) {
//                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
//                }
//            }
//            return super.dispatchTouchEvent(ev);
//        }
//
//        if (getWindow().superDispatchTouchEvent(ev)) {
//            return true;
//        }
//        return onTouchEvent(ev);
//    }
//    public  boolean isShouldHideInput(View v, MotionEvent event) {
//        if (v != null && (v instanceof EditText)) {
//            int[] leftTop = { 0, 0 };
//            v.getLocationInWindow(leftTop);
//            int left = leftTop[0];
//            int top = leftTop[1];
//            int bottom = top + v.getHeight();
//            int right = left + v.getWidth();
//            if (event.getX() > left && event.getX() < right
//                    && event.getY() > top && event.getY() < bottom) {
//                return false;
//            } else {
//                return true;
//            }
//        }
//        return false;
//    }

    /**
     * 获取数据
     * @param pageIndex 页码
     * @param pageCount 每页数量
     * @param searchStr 查询内容
     * @param type
     */
    private void getDataFromNet(final int pageIndex, int pageCount, String searchStr, String type) {
        RequestParams params = new RequestParams(IConstant.URL + "getAllStandardSearch");
        params.addBodyParameter("pageIndex", pageIndex+"");
        params.addBodyParameter("pageCount",pageCount+"");
        params.addBodyParameter("searchStr",searchStr);

        if(ckAll.getVisibility() == View.VISIBLE && ckQua.getVisibility() == View.VISIBLE
                && ckLive.getVisibility() == View.VISIBLE){
            if(ckAll.isChecked()){
                type = "全部";
            }else if(ckLive.isChecked()){
                type = "现场";
            }else if (ckQua.isChecked()){
                type = "质量";
            }
        }


        params.addBodyParameter("type",type);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //解析result
                progressDialog.dismiss();
                mList.clear();
                PaginationRegulations paginationRegulations = gson.fromJson(result, PaginationRegulations.class);
                if(paginationRegulations == null){
                    return;
                }
//                mCacheList = paginationRegulations.getFs();
//                for(Regulations rs : list){
//                    System.out.println(rs.getStandard()+rs.getCardNum()+rs.getRegulationNo());
//                }
                if(paginationRegulations.getCountNo() != null && paginationRegulations.getCountNo().size() > 0){
                    int count = paginationRegulations.getCountNo().get(0).getTotalCount();
                    if(count % pageSize == 0){
                        totalPages = count/pageSize;
                    }else{
                        totalPages = count/pageSize+1;
                    }
                }
                tvPageNum.setText(pageIndex+"");//当前页
                mList.addAll(paginationRegulations.getFs());
                regulationsDataAdapter.notifyDataSetChanged();//更新数据
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
            }
            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_refresh:
                et_regulations.setText("");
                searchStr = "";
                currentPage = 1;
                totalPages = 0;
                getDataFromNet(currentPage,pageSize,searchStr,type);
                break;
            case R.id.img_pre:
                if(totalPages == 0){
                    return;
                }
                if(currentPage == 1){
                    Toast.makeText(this,"已经第一页了",Toast.LENGTH_SHORT).show();
                    return;
                }
                currentPage = currentPage - 1;
                getDataFromNet(currentPage,pageSize,searchStr,type);
                break;
            case R.id.img_next:
                if(totalPages == 0){
                    return;
                }
                if(currentPage == totalPages){
                    Toast.makeText(this,"已经最后一页了",Toast.LENGTH_SHORT).show();
                    return;
                }
                currentPage = currentPage + 1;
                getDataFromNet(currentPage,pageSize,searchStr,type);
                break;
            case R.id.img_first:
                if(totalPages == 0){
                    return;
                }
                currentPage = 1;
                getDataFromNet(currentPage,pageSize,searchStr,type);
                break;
            case R.id.img_last:
                if(totalPages == 0){
                    return;
                }
                currentPage = totalPages;
                getDataFromNet(currentPage,pageSize,searchStr,type);
                break;

            case R.id.checkAll:
                if(ckAll.isChecked()){
                    ckLive.setChecked(false);
                    ckQua.setChecked(false);
                    getDataFromNet(1,10,"","全部");
                }else{
                    getDataFromNet(1,10,"","全部");
                }
                break;

            case R.id.checkLive:
                if(ckLive.isChecked()){
                    ckAll.setChecked(false);
                    ckQua.setChecked(false);
                    getDataFromNet(1,10,"","现场");
                }else{
                    getDataFromNet(1,10,"","全部");
                }
                break;

            case  R.id.checkQua:
                if(ckQua.isChecked()){
                    ckAll.setChecked(false);
                    ckLive.setChecked(false);
                    getDataFromNet(1,10,"","质量");
                }else{
                    getDataFromNet(1,10,"","全部");
                }
                break;

            case R.id.btn_reg_select:
                searchStr = et_regulations.getText().toString();
                currentPage = 1;
                getDataFromNet(currentPage,pageSize,searchStr,type);
                break;
        }
    }
}

